package com.caiwangdai.app.ui.verify

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import com.caiwangdai.app.Const
import com.caiwangdai.app.R
import com.caiwangdai.app.backend.RetrofitHome
import com.caiwangdai.app.backend.observer.OnDataV2Listener
import com.caiwangdai.app.backend.rx.RxSchedulers
import com.caiwangdai.app.bean.base.BaseB
import com.caiwangdai.app.bean.base.NormalResponseB
import com.caiwangdai.app.extension.getUser
import com.caiwangdai.app.extension.setOnClickListenerPro
import com.caiwangdai.app.extension.showMissingPermissionDialog
import com.caiwangdai.app.extension.toast
import com.caiwangdai.app.origin.BaseActivity
import com.caiwangdai.app.origin.ToolBarManager
import com.caiwangdai.app.utils.AndroidBug5497Workaround
import com.orhanobut.logger.Logger
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_idcard_info.*
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

/**
 * 身份信息
 */
class IDCardInfoActivity : BaseActivity() {
    var idCardRightSizeUploaded = false
    var idCardReverseSizeUploaded = false


    override fun getLayoutResID() = R.layout.activity_idcard_info

    companion object {

        fun newInstance(context: Context): Intent {
            val intent = Intent(context, IDCardInfoActivity::class.java)
            return intent
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        AndroidBug5497Workaround.assistActivity(this)//浸入式模式下，可以正常显示软键盘
    }


    override fun initView() {
        //toolbar
        ToolBarManager.with(this, WMContent)
                .setTitle("身份信息")
                .setNavigationIcon(R.drawable.ic_nav_arrow_white)

        //IdCard right-size
        rela_card_right.setOnClickListenerPro {
            takePicture(0)
        }
        //IdCard reverse-size
        rela_card_reverse.setOnClickListenerPro {
            takePicture(1)
        }
        //submit
        btn_submit.setOnClickListenerPro {
            if (checkAllValue()) actionSubmit()
        }
    }

    //0为身份证正面  1位身份证反面
    fun takePicture(IDCardType: Int) {
        RxPermissions(this)
                .request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe { granted ->
                    if (granted!!)
                        if (IDCardType == 0)
                            startActivityForResult(IdCardCameraActivity.newInstance(mContext, true), Const.INTENT_REQUEST_CARD_RIGHT_SIZE)
                        else
                            startActivityForResult(IdCardCameraActivity.newInstance(mContext, false), Const.INTENT_REQUEST_CARD_REVERSE_SIZE)
                    else
                        showMissingPermissionDialog("没有此权限，APP将无法正常访问摄像头!")
                }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        val uri = data?.getStringExtra("pic")
        Logger.e("uri=${uri}")

        when (requestCode) {

            Const.INTENT_REQUEST_CARD_RIGHT_SIZE -> {
                //正面
                updateImageFile(uri!!, 0)
            }

            Const.INTENT_REQUEST_CARD_REVERSE_SIZE -> {
                //反面
                updateImageFile(uri!!, 1)
            }

        }
    }

    var start: Long = 0;
    var end: Long = 0;

    //type=0为正面 type=1为背面
    fun updateImageFile(uri: String, cardType: Int) {

        val imageFile = File(uri)
        //传入multipartbody
        val image = MultipartBody.Part.createFormData("file", imageFile.getName(), RequestBody.create(MultipartBody.FORM, imageFile))
        val uid = MultipartBody.Part.createFormData("uid", getUser()?.id+"")
        val type = MultipartBody.Part.createFormData("type", if (cardType == 0) "idcarda" else "idcardb")

        start = System.currentTimeMillis()
        RetrofitHome.getUserApi()
                .postIdCard(image, uid, type)
                .compose(RxSchedulers.toMain())
                .subscribe(object : OnDataV2Listener<BaseB>(this) {
                    override fun getProgressBarContent() = "上传图片中..."
                    override fun onNext(value: NormalResponseB<BaseB>) {
                        super.onNext(value)
                        if (value.code != 200) return
                        end = System.currentTimeMillis()
                        Logger.e("相差时间${end - start}")
                        val bitmap = BitmapFactory.decodeFile(uri)
                        when (cardType) {
                            0 -> {
                                idCardRightSizeUploaded = true
                                iv_right_size.setImageBitmap(bitmap)
                            }
                            1 -> {
                                idCardReverseSizeUploaded = true
                                iv_reverse_size.setImageBitmap(bitmap)
                            }
                        }
                        //delete after used
                        imageFile.delete()

                    }
                })
    }

    fun checkAllValue(): Boolean {
        if (!idCardRightSizeUploaded) {
            toast("请上传正面身份证")
            return false
        }
        if (!idCardReverseSizeUploaded) {
            toast("请上传正面身份证")
            return false
        }
        return true
    }

    fun actionSubmit() {
        toast("上传身份证成功")
        startActivity(FaceVerifyReadyActivity.newInstance(mContext))
        onBackPressed()
    }


}
